package org.dandelion.memo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.dandelion.R;
import org.dandelion.memo.entity.Memo;

import java.time.format.DateTimeFormatter;
import java.util.List;

public class MemoAdapter extends ArrayAdapter<Memo> {
    private final int resourceId;

    private boolean checkable = false;

    public MemoAdapter(@NonNull Context context, int resource, @NonNull List<Memo> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Memo memo = getItem(position);
        View view;
        ViewHolder viewHolder;

        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId,
                    parent, false);
            viewHolder = new ViewHolder();
            viewHolder.titleTextView = view.findViewById(R.id.tv_title);
            viewHolder.dateTextView = view.findViewById(R.id.tv_date);
            viewHolder.checkBox = view.findViewById(R.id.selected_check_box);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.titleTextView.setText(memo.getTitle());
        viewHolder.dateTextView.setText(memo.getDateTime()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        if (checkable) {
            viewHolder.checkBox.setVisibility(View.VISIBLE);
        } else {
            viewHolder.checkBox.setVisibility(View.INVISIBLE);
        }

        viewHolder.checkBox.setChecked(((ListView) parent).isItemChecked(position));

        return view;
    }

    public void setCheckable(boolean checkable) {
        this.checkable = checkable;
    }

    private static class ViewHolder {
        TextView titleTextView;
        TextView dateTextView;
        CheckBox checkBox;
    }
}
